package readWriteLock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
//读写锁ReadWriteLock，可以一次多个读取
//读 ：（共享锁 ）  写：独占锁（别名）
public class ReadWriteLockDemo {
    public static void main(String[] args) {
        Mychche mychche = new Mychche();
        for (int i = 1; i < 6; i++) {
            final int temp = i;
            new Thread(() -> {
                mychche.put(temp,"111111");
            },String.valueOf(i)).start();
        }
        for (int i = 1; i < 6; i++) {
            final int temp = i;
            new Thread(() -> {
                mychche.get(temp);
            }, String.valueOf(i)).start();
        }
    }
}
//普通lock锁写入是ok的，读也是按顺序读
class Mychche{
    Lock lock = new ReentrantLock();
    Map<Integer, String> map = new HashMap<>();

    public void put(int key,String value){
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "开始写入");
            map.put(key, value);
            System.out.println(Thread.currentThread().getName() + "开始ok");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public void get(int key) {
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "开始读取");
            map.get(key);
            System.out.println(Thread.currentThread().getName() + "读取ok");
        }catch (Exception e){
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
//读写锁写是按顺序写，读是无顺序的可以多个一起读
class Mychche2 {
    ReadWriteLock lock = new ReentrantReadWriteLock();
    Map<Integer, String> map = new HashMap<>();

    public void put(int key, String value) {
        lock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "开始写入");
            map.put(key, value);
            System.out.println(Thread.currentThread().getName() + "开始ok");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.writeLock().unlock();
        }
    }

    public void get(int key) {
        lock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "开始读取");
            map.get(key);
            System.out.println(Thread.currentThread().getName() + "读取ok");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.writeLock().unlock();
        }
    }
}